<template>
	<view class="container">
		<!-- <view class="meter">
			<view class="needle" :style="'transform: rotate(' + needleAngle + 'deg)'"></view>
			<view class="scale"></view>
			<view class="center-circle"></view>
		</view> -->
		<view class="meter" style="position: relative; width: 690rpx;height: 220rpx; margin: 0 auto;">
			<image class="dashboard-bg" src="/static/image/Dashboard.png"
				style="width: 100%; height: 100%; position: absolute; left: 0; top: 0;" mode="aspectFit" />
			<image class="needle" src="/static/image/Pointer.png" :style="{
						position: 'absolute',
						left: '50%',
						top: '120%',
						width: '40rpx', // 根据你的指针图片实际宽高调整
						height: '296rpx',
						transform: 'translate(-50%, -90%) rotate(' + needleAngle + 'deg)',
						'transform-origin': '50% 90%' // 指针底部为旋转中心
					}" mode="aspectFit" />
			<!-- <view class="center-circle"></view> -->
		</view>
		<view class="info">
			<text>当前频率: {{ currentFreq }} Hz</text>
			<text>目标频率: {{ targetFreq }} Hz</text> 
			<text>状态: {{ statusText }}</text>

		</view>
		<button @click="startListening" :disabled="isListening">开始检测</button>
		<button @click="stopListening" :disabled="!isListening">停止检测</button>
		<input type="number" placeholder="输入目标频率(Hz)" v-model="targetFreq" />
	</view>
</template>

<script>
	import {
		analyzeFrequency
	} from '@/utils/audioAnalyzr.js'

	export default {
		data() {
			return {
				currentFreq: 0,
				targetFreq: 65,
				needleAngle: 0,
				statusText: '等待检测...',
				isListening: false,
				timer: null,
				recorderManager: null,
				onStopRegistered: false
			}
		},
		methods: {
			async startListening() {
				if (this.isListening) return;
				this.isListening = true;
				clearInterval(this.timer);
				this.timer = null;

				this.recorderManager = uni.getRecorderManager();
				if (!this.onStopRegistered) {
					this.recorderManager.onStop(this.handleRecorderStop);
					this.onStopRegistered = true;
				}

				// 立即开始第一次录音
				this.recorderManager.start({
					format: 'PCM',
					sampleRate: 44100,
					numberOfChannels: 1,
					encodeBitRate: 96000
				});

				// 定时 stop 录音，触发 onStop 分析
				this.timer = setInterval(() => {
					if (this.isListening && this.recorderManager) {
						this.recorderManager.stop();
					}
				}, 150); // 200ms 实时刷新
				this.statusText = '检测中...';
			},
			stopListening() {
				if (!this.isListening) return;
				this.isListening = false;
				clearInterval(this.timer);
				this.timer = null;
				this.statusText = '已停止';
				if (this.recorderManager) {
					this.recorderManager.stop();
				}
			},
			async handleRecorderStop(res) {
				// 分析音频
				setTimeout(async () => {
					try {
						const arrayBuffer = await this.readFileAsArrayBuffer(res.tempFilePath)
						let ab = arrayBuffer;
						if (ab.byteLength % 2 !== 0) {
							ab = ab.slice(0, ab.byteLength - 1);
						}
						const int16Data = new Int16Array(ab)
						let floatBuffer = new Float32Array(int16Data.length);
						for (let i = 0; i < int16Data.length; i++) {
							floatBuffer[i] = int16Data[i] / 32768;
						}
						let shortBuffer = floatBuffer.slice(0, 8192);
						const frequency = analyzeFrequency(shortBuffer, 44100)
						if (isNaN(frequency) || frequency <= 0 || frequency > 2000) {
							this.currentFreq = '-';
							this.statusText = '无信号';
							this.needleAngle = -70; // 指针回到最左侧
						} else {
							this.updateUI(frequency)
						}
						// 实时检测：分析完后立即重新开始录音
						if (this.isListening) {
							this.recorderManager.start({
								format: 'PCM',
								sampleRate: 44100,
								numberOfChannels: 1,
								encodeBitRate: 96000
							});
						}
					} catch (err) {
						console.error('分析音频失败:', err)
					}
				}, 30)
			},
			readFileAsArrayBuffer(filePath) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: filePath,
						success: res => resolve(res.data),
						fail: reject
					})
				})
			},
			updateUI(detectedFreq) {
				const diff = detectedFreq - this.targetFreq
				let angle = 0
				let status = ''
				const minAngle = -70
				const centerAngle = 0
				const maxAngle = 70
				const maxDiff = this.targetFreq * 0.1 // ±10%的范围

				if (diff <= -maxDiff) {
					angle = minAngle
				} else if (diff >= maxDiff) {
					angle = maxAngle
				} else {
					angle = centerAngle + (diff / maxDiff) * (maxAngle - centerAngle)
				}

				if (Math.abs(diff) < this.targetFreq * 0.01) {
					status = '音高准确'
				} else if (diff > 0) {
					status = '偏高'
				} else {
					status = '偏低'
				}
				this.currentFreq = detectedFreq.toFixed(2)
				this.needleAngle = angle
				this.statusText = status
			}
		},
		beforeDestroy() {
			this.stopListening()
		}
	}
</script>

<style lang="scss">
	@import './index.scss';
</style>